<?php

namespace app\api\controller;

use app\api\exception\ApiException;
use app\api\model\User;
use app\api\validate\AccessTokenValidate;
use app\common\lib\Identity;
use think\facade\Cache;

class AccessToken extends ApiController
{
	/**
	 * 生成access_token
	 * @return \think\Response
	 * @throws ApiException
	 */
	public function generate(){
		$data = (new AccessTokenValidate())->go($this->request->get(),__FUNCTION__);
		$appid = $data['appid'];
		$secret = $data['secret'];

		$user = User::getUserByIdentity($appid,$secret);
        try{
            User::chkIp($this->request->ip(),$user);
        }catch (\Exception $exception){
            throw new ApiException($exception->getMessage());
        }
		if(Cache::has($appid.Identity::ACCESS_TOKEN_KEY)){
			$data = Cache::get($appid.Identity::ACCESS_TOKEN_KEY);
			return $this->response->success([
				'access_token' => $data['access_token'],
				'expire_in' => (7200+$data['time']) - time()
			]);
		}
		$accessToken = Identity::accessToken($appid,$secret);

		return $this->response->success([
			'access_token' => $accessToken,
			'expire_in' => 7200
		]);
	}

	/**
	 * 刷新access_token
	 * @return \think\Response
	 * @throws ApiException
	 * @throws \think\Exception
	 */
	public function refresh(){
		$data = (new AccessTokenValidate())->go($this->request->get());
		$appid = $data['appid'];
		$secret = $data['secret'];
		$accessToken = $data['access_token'];

		if(!Cache::has($appid.Identity::ACCESS_TOKEN_KEY)){
			throw new ApiException('access_token已过期');
		}

        $user = User::getUserByIdentity($appid,$secret);
        try{
            User::chkIp($this->request->ip(),$user);
            $accessToken = Identity::refreshAccessToken($appid,$secret,$accessToken);
        }catch (\Exception $exception){
            throw new ApiException($exception->getMessage());
        }

		return $this->response->success($accessToken);
	}
}
